<template>
  <div class="alert-list-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Warning /></el-icon>
            预警列表
          </span>
          <div class="card-actions">
            <el-button type="success" size="small" @click="markAllAsRead">
              <el-icon><Check /></el-icon>
              全部标记已读
            </el-button>
            <el-button type="danger" size="small" @click="clearAllAlerts">
              <el-icon><Delete /></el-icon>
              清空预警
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选器 -->
      <div class="filter-bar">
        <el-form :model="filters" inline>
          <el-form-item label="预警类型">
            <el-select
              v-model="filters.alertType"
              placeholder="选择预警类型"
              clearable
              style="width: 150px"
            >
              <el-option label="安全预警" value="security" />
              <el-option label="网络预警" value="network" />
              <el-option label="流量预警" value="traffic" />
              <el-option label="离线预警" value="offline" />

              <el-option label="行为预警" value="behavior" />

<!--              <el-option label="视频分析" value="video" />-->
            </el-select>
          </el-form-item>
          <el-form-item label="严重程度">
            <el-select
              v-model="filters.severity"
              placeholder="选择严重程度"
              clearable
              style="width: 120px"
            >
              <el-option label="低" value="1" />
              <el-option label="中" value="2" />
              <el-option label="高" value="3" />
              <el-option label="紧急" value="4" />
              <el-option label="严重" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadAlerts">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预警表格 -->
      <el-table :data="alertsList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="alertType" label="预警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeColor(row.alertType)">
              {{ getAlertTypeName(row.alertType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clientName" label="客户端" width="150" />
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityColor(row.severity)" size="small">
              {{ getSeverityName(row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="预警描述" min-width="300">
          <template #default="{ row }">
            <div class="alert-description">
              <el-icon :class="['alert-icon', getAlertIconClass(row.alertType)]">
                <component :is="getAlertIcon(row.alertType)" />
              </el-icon>
              <span>{{ row.description }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发生时间" width="160">
          <template #default="{ row }">
            {{ formatAlertTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="resolved" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.resolved ? 'success' : 'warning'" size="small">
              {{ row.resolved ? '已处理' : '待处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="!row.resolved"
                type="success"
                size="small"
                @click="resolveAlert(row)"
              >
                <el-icon><Check /></el-icon>
                标记已处理
              </el-button>
              <el-button type="primary" size="small" @click="viewAlertDetail(row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button type="danger" size="small" @click="deleteAlert(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <el-empty
        v-if="alertsList.length === 0 && !loading"
        description="暂无预警信息"
        :image-size="100"
      />
    </el-card>

    <!-- 预警详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="预警详情" width="600px">
      <div v-if="selectedAlert" class="alert-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预警类型">
            <el-tag :type="getAlertTypeColor(selectedAlert.alertType)">
              {{ getAlertTypeName(selectedAlert.alertType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityColor(selectedAlert.severity)">
              {{ getSeverityName(selectedAlert.severity) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户端">{{ selectedAlert.clientName }}</el-descriptions-item>
          <el-descriptions-item label="发生时间">{{ formatAlertTime(selectedAlert.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="状态" :span="2">
            <el-tag :type="selectedAlert.resolved ? 'success' : 'warning'">
              {{ selectedAlert.resolved ? '已处理' : '待处理' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预警描述" :span="2">
            {{ selectedAlert.description }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedAlert.detail" label="详细信息" :span="2">
            <pre class="alert-detail-text">{{ selectedAlert.detail }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
          v-if="selectedAlert && !selectedAlert.resolved"
          type="success"
          @click="resolveAlert(selectedAlert)"
        >
          标记已处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Warning, Check, Delete, Search, View,
  Monitor, DataLine, Lock, Timer, Document, VideoPlay
} from '@element-plus/icons-vue'
import { alertsService } from '@/services/dataService.js'
import { getAlertTypeName as getTypeName, getAlertTypeColor } from '@/config/app.js'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedAlert = ref(null)

// 筛选器
const filters = reactive({
  alertType: '',
  severity: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 预警列表数据
const alertsList = ref([])

// 格式化时间函数 - 将ISO 8601格式转换为 YYYY/MM/DD HH:mm:ss 格式
const formatAlertTime = (timeString) => {
  try {
    const date = new Date(timeString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timeString
  }
}

// 方法
const getAlertTypeName = (type, subtype = null) => {
  // 使用新的统一映射函数
  return getTypeName(type, subtype)
}



const getSeverityName = (severity) => {
  const severityMap = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急',
    5: '严重'
  }
  return severityMap[severity] || severity
}

const getSeverityColor = (severity) => {
  const colorMap = {
    1: 'info',
    2: 'primary',
    3: 'warning',
    4: 'danger',
    5: 'danger'
  }
  return colorMap[severity] || 'info'
}

const getAlertIcon = (type) => {
  const iconMap = {
    security: Warning,
    network: Lock,
    traffic: DataLine,
    offline: Monitor,
    software: Delete,
    inactivity: Timer,
    file_transfer: Document,
    video: VideoPlay
  }
  return iconMap[type] || Warning
}

const getAlertIconClass = (type) => {
  return `alert-icon-${type}`
}

const loadAlerts = async () => {
  try {
    loading.value = true

    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    // 添加筛选条件
    if (filters.alertType) {
      params.type = filters.alertType
    }
    if (filters.severity) {
      params.severity = filters.severity
    }
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }

    const response = await alertsService.getAlerts(params)
    console.log('API响应:', response) // 添加调试日志

    // 修复：检查response.code === 200 而不是 response.success
    if (response.code === 200 && response.data) {
      // 转换API数据格式为组件需要的格式
      alertsList.value = response.data.list.map(alert => ({
        id: alert.id,
        alertType: alert.type,
        clientId: alert.client_id,
        clientName: alert.client_name,
        severity: alert.severity,
        description: alert.description,
        detail: alert.detail || alert.description,
        createdAt: alert.created_at,
        resolved: alert.resolved
      }))

      pagination.total = response.data.total
      console.log('处理后的数据:', alertsList.value) // 添加调试日志
    } else {
      console.error('API响应格式错误:', response)
      ElMessage.error('数据格式错误')
    }
  } catch (error) {
    console.error('加载预警列表失败:', error)
    ElMessage.error('加载预警列表失败')
  } finally {
    loading.value = false
  }
}

const viewAlertDetail = async (alert) => {
  try {
    loading.value = true
    const response = await alertsService.getAlert(alert.id)

    // 修复：检查response.code === 200 而不是 response.success
    if (response.code === 200 && response.data) {
      selectedAlert.value = {
        ...response.data,
        alertType: response.data.type,
        clientId: response.data.client_id,
        clientName: response.data.client?.name || alert.clientName,
        createdAt: response.data.created_at
      }
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取预警详情失败')
    }
  } catch (error) {
    console.error('获取预警详情失败:', error)
    ElMessage.error('获取预警详情失败')
  } finally {
    loading.value = false
  }
}

const resolveAlert = async (alert) => {
  try {
    const response = await alertsService.resolveAlert(alert.id, {
      note: '已确认并处理该预警'
    })

    // 修复：检查response.code === 200 而不是 response.success
    if (response.code === 200) {
      alert.resolved = true
      ElMessage.success('预警已标记为已处理')
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
      // 重新加载列表
      await loadAlerts()
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('处理预警失败:', error)
    ElMessage.error('操作失败')
  }
}

const deleteAlert = async (alert) => {
  try {
    await ElMessageBox.confirm('确定要删除此预警吗？', '确认删除', { type: 'warning' })

    const response = await alertsService.deleteAlert(alert.id)

    if (response.code === 200) {
      ElMessage.success('预警删除成功')
      await loadAlerts()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除预警失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm('确定要将所有预警标记为已读吗？', '确认操作', { type: 'warning' })

    const response = await alertsService.markAllAlertsAsRead()

    if (response.code === 200) {
      ElMessage.success(`已标记 ${response.data.processed} 条预警为已读`)
      await loadAlerts()
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记已读失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const clearAllAlerts = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有预警吗？此操作不可恢复！', '确认清空', { type: 'warning' })

    const response = await alertsService.clearAllAlerts()

    if (response.code === 200) {
      ElMessage.success(`已清空 ${response.data.deleted} 条预警`)
      await loadAlerts()
    } else {
      ElMessage.error('清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空预警失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadAlerts()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadAlerts()
}

// 生命周期
onMounted(() => {
  loadAlerts()
})
</script>

<style scoped>
.alert-list-page {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 增大筛选框的标签字号 */
.filter-bar :deep(.el-form-item__label) {
  font-size: 16px !important;
  font-weight: 500;
}

/* 增大筛选框输入控件的字号 */
.filter-bar :deep(.el-input__inner),
.filter-bar :deep(.el-select .el-input__inner) {
  font-size: 15px !important;
}

/* 增大日期选择器的字号 */
.filter-bar :deep(.el-date-editor .el-input__inner) {
  font-size: 15px !important;
}

/* 增大筛选框下拉选项的字号 */
.filter-bar :deep(.el-select-dropdown__item) {
  font-size: 15px !important;
}

/* 增大表格列标题的字号 - 这个页面特定的设置 */
.alert-list-page :deep(.el-table th .cell) {
  font-size: 16px !important;
  font-weight: 600;
}

.alert-description {
  display: flex;
  align-items: center;
  gap: 8px;
}

.alert-icon {
  font-size: 16px;
}

.alert-icon-security {
  color: #F56C6C;
}

.alert-icon-network {
  color: #409EFF;
}

.alert-icon-traffic {
  color: #E6A23C;
}

.alert-icon-offline {
  color: #F56C6C;
}

.alert-icon-software {
  color: #909399;
}

.alert-icon-inactivity {
  color: #E6A23C;
}

.alert-icon-file_transfer {
  color: #F56C6C;
}

.alert-icon-video {
  color: #67C23A;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  flex-wrap: nowrap;
  min-width: 220px;
  padding: 4px 0;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: 64px;
  height: 32px;
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button .el-icon {
  margin-right: 4px;
  font-size: 12px;
}

.action-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 确保按钮文字不换行 */
.action-buttons .el-button span {
  white-space: nowrap;
}

.alert-detail-text {
  white-space: pre-wrap;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>
